<template>
	<view class="page" :style="{paddingTop: `${topHeight}px`}" style="height: 93.5vh;display: flex;flex-direction: column;">
		<view class="header">
			<view class="h-l">
				<uni-icons type="left" size="22" @tap="goBack"></uni-icons>
			</view>
			<view class="h-c">
				<text>{{templete.name}}</text>
			</view>
			<view class="h-r">
				<uni-icons type="more-filled" size="20" @click="toMore"></uni-icons>
			</view>
		</view>
		<view class="content">
			<scroll-view scroll-y="true" class="scroll-view">
				<view style="padding: 10rpx 20rpx;text-align: right;color: #909399;">
					<text v-if="!isEdit" style="font-size: 28rpx;">{{draftMsg}}</text>
				</view>
				<view class="content-item">
					<view class="textarea" v-for="(f,index) in fieldList" :key="index">
						<view style="font-weight: bold;">{{f.field_name}}</view>
						<view>
							<RichEditor ref="myEditor" :editorId="'editor'+index" :editorDetail="f.field_content" @getContents="getContents" class="bg" v-if="f.field_type=='quill'"></RichEditor>
							<textarea v-model="f.field_content" placeholder="请输入" v-else placeholder-style="color:#00000099;font-style:italic;" auto-height="true" @blur="handleBlur"></textarea>
						</view>
					</view>
				</view>
				<view class="content-item">
					<view class="item-list-image">
						<text style="width: 100rpx;">图片</text>
						<view style="width: 100vw;position: relative;">
							<up-upload
								:fileList="imageList"
								@afterRead="afterRead"
								@delete="deletePic"
								name="3"
								multiple
								:maxCount="12"
								:previewFullImage="true"
							>
								<uni-icons type="image" size="30" color="#3f85ff" style="position: absolute;right: 0;top: 0;"></uni-icons>
							</up-upload>
						</view>
					</view>
					<view class="item-list-file">
						<text style="width: 100rpx;">附件</text>
						<view style="display: flex;flex-direction: row;align-items: center;width: 100vw;">
							<!-- 文件列表独立展示 -->
							<view class="file-list-container" style="width: auto;">
								<view class="file-item" v-for="(item,index) in fileList" :key="index" style="display: flex;flex-direction: row;font-size: 26rpx;color: #909399;">
									<text class="file-name" @click="FileViewClick(item)">{{item.name}}</text>
									<view class="remove-btn" @click="clear(item.name)">
										<up-icon name="close-circle-fill" size="20" color="#ff4d4f"></up-icon>
									</view>
								</view>
							</view>
							<lsj-upload ref="lsjUpload" childId="upload1" :Displayornot="false"
										:option="option" :size="100" :count="2" :formats="formats" 
										:debug="false" :instantly="true" @uploadEnd="uploadEnd" style="width: 50rpx;position: absolute;right: 24rpx;">
								<uni-icons type="paperclip" size="28" color="#3f85ff"></uni-icons>
							</lsj-upload>
						</view>
					</view>
				</view>
				<!-- <view class="content-item">
					<view class="item-list">
						<text>所在位置</text>
						<view style="font-size: 26rpx;color: #909399;">{{location}}</view>
						<uni-icons type="location" size="30" color="#3f85ff" @click="getLocation"></uni-icons>
					</view>
				</view> -->
				<view v-if="!isEdit">
					<view class="item-list">
						<text>发送到人</text>
						<uni-icons type="plus" size="30" color="#3f85ff" @click="selectPerson"></uni-icons>
					</view>
					<scroll-view scroll-x="true" class="person-list">
						<view v-for="(p,pidx) in personList" style="display: inline-block;padding-top: 20rpx;">
							<view class="person-item">
								<image :src="p.avatar"></image>
								<text style="font-size: 26rpx;color:#909399">{{p.name}}</text>
								<view class="close-btn" @click="delPerson(pidx)">
									<uni-icons type="close" size="18" color="#909399"></uni-icons>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<view v-if="!isEdit" style="padding: 0 20rpx;">
					<up-checkbox-group v-model="chatCheckbox">
						<up-checkbox shape="circle" label="同时通过聊天发送给对方"></up-checkbox>
					</up-checkbox-group>
				</view>
				<view style="margin-bottom: 10rpx">
					<view style="background-color: #fff;padding: 20rpx;display: flex;justify-content: space-between;align-items: center;">
						<text>仅接收人可见，不可转发</text>
						<switch @change="switch2Change" />
					</view>
				</view>
				<view style="padding: 0 20rpx 50rpx 20rpx;">
					<text style="font-size: 28rpx;color: #606266;">除了你自己，任何人不可转发你的日志内容</text>
				</view>
			</scroll-view>
			<view class="bottom">
				<view class="left" @click="lookLog">
					<image class="TabItemICon" src="../../static/icon/look.svg"></image>
					<text style="font-size: 22rpx;color: #909399;margin-top: 5rpx;">看日志</text>
				</view>
				<view class="right">
					<button :disabled="disabled" type="primary" @click="doSubmit" style="line-height: 2;">{{isEdit?'编辑':'提交'}}日志</button>
				</view>
			</view>
		</view>

		<!--弹层-->
		<up-popup :show="showMore" :round="10" mode="center"  @close="closeMore">
			<view style="padding: 40rpx;width: 50vw;font-size: 28rpx;z-index: 99;">
				<view style="margin-bottom: 40rpx;" @click="importLastLog">导入上篇</view>
				<view style="margin-bottom: 40rpx;color: #909399;">发送模板给他人填写</view>
				<view style="margin-bottom: 40rpx;color: #909399;">生成模板二维码</view>
				<view style="width: 100rpx;float: right;margin-bottom: 20rpx;">
					<up-button type="primary" :plain="true" text="取消" @tap="closeMore" :customStyle="{height:'30px'}"></up-button>
				</view>
			</view>
		</up-popup>
		<up-popup :show="showBack" :round="10" mode="center"  @close="closeBack">
			<view style="padding: 20rpx 40rpx;width: 50vw;font-size: 28rpx;z-index: 99;">
				<view style="margin-bottom: 30rpx;color: #909399;font-size: 24rpx;">草稿已自动保存</view>
				<view style="margin-bottom: 40rpx;">你需要退出，稍后填写吗？</view>
				<view style="width: 50vw;float: right;margin-bottom: 20rpx;display: flex;flex-direction: row;">
					<up-button type="text" style="color: #3f85ff;" :plain="true" text="退出" @tap="confirmBack" :customStyle="{height:'30px'}"></up-button>
					<up-button type="text" style="color: #909399;" :plain="true" text="取消" @tap="closeBack" :customStyle="{height:'30px'}"></up-button>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script>
	import log from '@/apis/cloud/worklog';
	import RichEditor from '@/components/editor/editor.vue';
	import { getCurrentInstance} from "vue";
	import { useUserStore } from '@/pinia-store/user'
	import { mapStores } from 'pinia'
	import { COMMON_API_BASE_URL } from '@/utils/request'
	import dayjs from "dayjs"
	var _this;
	export default {
		name:'LogTemplete',
		components: {
			RichEditor
		},
		data() {
			return {
				draftMsg:'所写内容会实时保存',
				disabled:false,
				topHeight: 0,
				showMore:false,
				showBack:false,
				userInfo: {},
				templete: {},
				fieldList:[],
				templete1:[
					{field_name:'今日完成工作',field_value:'field_1',field_type:'quill',field_content:''},
					{field_name:'未完成工作',field_value:'field_2',field_type:'quill',field_content:''},
					{field_name:'需协调工作',field_value:'field_3',field_type:'quill',field_content:''},
					{field_name:'备注',field_value:'field_4',field_type:'textarea',field_content:''},
				],
				templete2:[
					{field_name:'本周完成工作',field_value:'field_1',field_type:'quill',field_content:''},
					{field_name:'本周工作总结',field_value:'field_2',field_type:'quill',field_content:''},
					{field_name:'下周工作计划',field_value:'field_7',field_type:'quill',field_content:''},
					{field_name:'需协调工作',field_value:'field_3',field_type:'quill',field_content:''},
					{field_name:'备注',field_value:'field_4',field_type:'textarea',field_content:''},
				],
				templete3:[
					{field_name:'本月工作内容',field_value:'field_1',field_type:'quill',field_content:''},
					{field_name:'本月工作总结',field_value:'field_2',field_type:'quill',field_content:''},
					{field_name:'下月工作计划',field_value:'field_7',field_type:'quill',field_content:''},
					{field_name:'需协调工作',field_value:'field_3',field_type:'quill',field_content:''},
					{field_name:'备注',field_value:'field_4',field_type:'textarea',field_content:''},
				],
				isEdit:false,
				logObj:{},
				chatCheckbox:'',
				personList:[],
				// 上传接口参数
				option: {
					// 上传服务器地址，需要替换为你的接口地址
					url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
					// 上传附件的key
					name: 'file',
					// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
					// header: {},
					// 根据你接口需求自定义body参数
					formData: {
						// 'orderId': 1000
						token: ''
					},
				},
				// 限制允许上传的格式，空串=不限制，默认为空
				formats: 'docx,doc,pdf,jpeg,jpg,png,gif,ppt,pptx,xls,xlsx',
				fileList:[],
				imageList:[],
				location:'',
			}
		},
		computed: {
		  ...mapStores(useUserStore)
		},
		mounted() {
			//用户信息
			_this.userInfo = _this.userStore.user;
			_this.option.formData.token = _this.userStore.user.token;
		},
		created(){
			//关闭选择人员
			uni.$off('WorklogAddUser');
			_this = this;
			let app = uni.getSystemInfoSync();
			_this.topHeight = app.statusBarHeight;
			_this.fieldList = _this.templete1;
			//监听选择人员信息
			uni.$on('WorklogAddUser',(data)=>{
				if(_this.personList && _this.personList.length > 0) {
					data.forEach(p=>{
						_this.personList.push(p);
					});
					//去重
					const seen = new Map();
					_this.personList = _this.personList.filter(item=>{
						return !seen.has(item.id) && seen.set(item.id, true);
					});
				}else {
					_this.personList = data;
				}
				_this.disabled = false;
			});

		},
		onLoad(options) {
			const instance = getCurrentInstance().proxy;
			const eventChannel = instance.getOpenerEventChannel();
			eventChannel.on('writeParams', async function(data) {
				//日志模板
				_this.templete = data.templete;
				if(_this.templete.id == 1) {
					_this.fieldList = _this.templete1;
				}else if(_this.templete.id == 2){
					_this.fieldList = _this.templete2;
				}else if(_this.templete.id == 3){
					_this.fieldList = _this.templete3;
				}
				//获取最新一条日志，为了填写发送到人
				_this.getLatestLog();

				//编辑
				_this.logObj = data.logObj;
				if(_this.logObj) {
					_this.isEdit = true;
					_this.templete.name = '编辑'+data.logObj.add_name+'的'+data.logObj.templete_name;
					let fieldList = JSON.parse(data.logObj.content);
					//附件处理
					fieldList.forEach(f=>{
						if(f.field_name=='图片') {
							_this.imageList = JSON.parse(f.field_content)
						}
						if(f.field_name=='附件') {
							_this.fileList = JSON.parse(f.field_content)
						}
					});
					if(data.templete.id == 1) {
						_this.templete1.forEach(item=>{
							fieldList.forEach(f=>{
								if(item.field_value == f.field_value) {
									item.field_content = f.field_content;
								}
							});
						});
					}else if(data.templete.id == 2) {
						_this.templete2.forEach(item=>{
							fieldList.forEach(f=>{
								if(item.field_value == f.field_value) {
									item.field_content = f.field_content;
								}
							});
						});
					}else if(data.templete.id == 3) {
						_this.templete3.forEach(item=>{
							fieldList.forEach(f=>{
								if(item.field_value == f.field_value) {
									item.field_content = f.field_content;
								}
							});
						});
					}
				}else {
					//获取草稿
					let draft = uni.getStorageSync('logContent'+data.templete.id)
					if(draft) {
						_this.fieldList = JSON.parse(draft);

						let dateHm = dayjs().format('HH:mm');
						_this.draftMsg = '实时保存，保存时间'+dateHm;
					}
				}
			});
		},
		onBackPress(options) {
			if(options.from === 'backbutton' && !_this.isEdit) {
				let editors = Array.isArray(_this.$refs.myEditor) ? _this.$refs.myEditor : [_this.$refs.myEditor];
				editors.forEach(item=>{
					item.handleEditorBlur();
				});
				_this.showBack = true;
				return true;
			}

		},
		methods: {
			async getLatestLog() {
				const params = {
					row: 1,
					page: 1,
					type: 1,
					add_phone: _this.userInfo.phone,
				};
				const res = await log.getList(params);
				if(res.status > 0) {
					let data = res.data;
					if(data && data.length > 0) {
						let lookPeopleList = JSON.parse(data[0].sendToPeople);
						lookPeopleList.forEach(p=>{
							_this.personList.push({id:p.worker_id,name:p.worker_name,avatar:p.img_url,type:'user'});
						});
					}
				}
			},
			toMore() {
				_this.showMore = true;
			},
			closeMore() {
				_this.showMore = false;
			},
			//导入上篇
			importLastLog() {
				_this.showMore = false;
				uni.showModal({
					title: '提示',
					content: '导入上篇日报？导入会覆盖正在编辑的内容',
					success: function (res) {
						if (res.confirm) {
							//console.log('用户点击确定');
							_this.importLog();
						} else if (res.cancel) {
							//console.log('用户点击取消');
						}
					}
				});
			},
			async importLog() {
				const params = {
					row: 1,
					page: 1,
					type: 1,
					add_phone: _this.userInfo.phone,
					templete_name:_this.templete.name,
				};
				const res = await log.getList(params);
				if(res.status > 0) {
					let data = res.data;
					if(data && data.length > 0) {
						let logList = JSON.parse(data[0].content);
						_this.fieldList.forEach(item=>{
							logList.forEach(log=>{
								if(item.field_value == log.field_value) {
									item.field_content = log.field_content;
								}
							});
						});
					}else {
						uni.$u.toast('导入失败，赶紧写篇试试');
					}
				}
			},
			//获取富文本内容
			getContents(data){
				let index =Number(data.editorId.replace('editor',''));
				_this.fieldList[index].field_content = data.content;
				_this.disabled = false;

				//保存草稿
				if(!_this.isEdit) {
					let dateHm = dayjs().format('HH:mm');
					_this.draftMsg = '实时保存，保存时间'+dateHm;
					uni.setStorageSync('logContent'+_this.templete.id, JSON.stringify(_this.fieldList));
				}
			},
			//获取textarea内容
			handleBlur(e) {
				//保存草稿
				if(!_this.isEdit) {
					let dateHm = dayjs().format('HH:mm');
					_this.draftMsg = '实时保存，保存时间'+dateHm;
					uni.setStorageSync('logContent'+_this.templete.id, JSON.stringify(_this.fieldList));
				}
			},
			//上传附件
			uploadEnd(res) {
				if(res.type == 'success' && res.responseText) {
					const responseText = JSON.parse(res.responseText);
					_this.fileList.push(responseText.data);
				}
			},
			// 移除某个文件
			clear(name) {
				// name=指定文件名，不传name默认移除所有文件
				// this.$refs.lsjUpload.clear(name);
				const findIndex = _this.fileList.findIndex(item => item.name == name)
				_this.fileList.splice(findIndex, 1);
				//this.$emit('ok', {fileList: _this.fileList, index: _this.itemIndex});
			},
			// 查看文件
			FileViewClick (item) {
				let name = item?.name?.split('.').pop() || item?.filename?.split('.').pop()
				if(name == 'png' || name == 'jpg' || name == 'jpeg' || name == 'gif' || name == 'bmp' || name == 'webp' || name == 'svg'){
					uni.previewImage({
						urls: [item.url],
					})
				}else{
					let url = item.url || `${COMMON_API_BASE_URL}${item.path}`;
					let name = item.name || item.filename;
					uni.navigateTo({
						url: `/pages/chat/message/previewDoc?fileName=${name}&url=${url}`,
					})
				}
			},
			//上传图片
			async afterRead(e) {
				e.file.forEach((item) => {
					// 先 push 到 fileList，记录当前位置
					/*_this.imageList.push({
						...item,
						status: "success",
						message: "",
					});
					const currentIndex = _this.imageList.length - 1; // 获取刚 push 进去的图片索引
					*/
					uni.uploadFile({
						url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
						filePath: item.url,
						name: 'file',
						formData: {
							'token': _this.userInfo.token
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							// 正确设置 fileList 中刚上传的项
							_this.imageList.push({
								url: data.data.url,
								id: data.data.id,
								name: data.data.name,
								status: 'success',
								message: '',
							});
						},
						fail: (err) => {
							_this.imageList.push({
								...item,
								status: 'failed',
								message: '上传失败',
							});
						}
					});
				});
			},
			//删除图片
			deletePic(event) {
				_this.imageList.splice(event.index, 1);
			},
			//获取位置
			getLocation() {
				uni.getLocation({
					type: 'gcj02', // 坐标系类型
					geocode: true,
					accuracy: 'high',
					success: function (res) {
						//高德逆地址编码，获取详细信息
						uni.request({
							header: {
								'Content-Type': 'application/text',
							},
							//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
							url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON
								&location=${res.longitude},${res.latitude}&key=bf4975e1b40f054300eeb2ddc50aa243`,
							success(resData) {
								if(resData.statusCode == 200) {
									_this.location = resData.data.regeocode.formatted_address;
								}
							}
						})

					},
					fail: function (res) {
					  console.log('获取定位失败：' + res.errMsg);
					}
				});
			},
			goBack () {
				if(_this.isEdit || _this.draftMsg == '所写内容会实时保存') {
					uni.navigateBack({ delta: 1 });
				}else {
					/*
					uni.showModal({
						title: '草稿已自动保存',
						content: '你需要退出，稍后填写吗？',
						success: function (res) {
							if (res.confirm) {
								//console.log('用户点击确定');
								uni.navigateBack({ delta: 1 });
							} else if (res.cancel) {
								//console.log('用户点击取消');
							}
						}
					});*/
					_this.showBack = true;
				}
			},
			confirmBack() {
				uni.navigateBack({ delta: 1 });
			},
			closeBack() {
				_this.showBack = false;
			},
			switch2Change(e) {

			},
			async doSubmit() {
				_this.disabled = true;
				// let editor = JSON.parse(JSON.stringify(_this.$refs.myEditor));
				let editors = Array.isArray(_this.$refs.myEditor) ? _this.$refs.myEditor : [_this.$refs.myEditor];

				editors.forEach((item,index)=>{
					let content = item.editorDetailNew?item.editorDetailNew:item.editorDetail;
					_this.fieldList[index].field_content = content;
				});
				//日志内容
				let content = JSON.stringify(_this.fieldList[0].field_content);
				if(!content || content == '""') {
					uni.$u.toast(_this.fieldList[0].field_name+'未填写');
					return;
				}
				let logContents = JSON.parse(JSON.stringify(_this.fieldList));
				//图片
				logContents.push({field_name:'图片',field_value:'field_6',field_type:'image',
					field_content:JSON.stringify(_this.imageList)});
				//附件
				logContents.push({field_name:'附件',field_value:'field_5',field_type:'file',
					field_content:JSON.stringify(_this.fileList)});
				//选择人员
				let person = [];
				if(!_this.isEdit) {
					if(_this.personList && _this.personList.length > 0) {
						_this.personList.forEach(p=>{
							person.push(p.id);
						});
					}else {
						uni.$u.toast('请选择发送到人');
						return;
					}

					const params = {
						content: JSON.stringify(logContents),
						look_people: person.join(','),
						chat_checked: false,//是否发送到聊天
						send_qun: '',
						share_checked: false,//是否转发
						status: false,//是否定时发送
						send_time: '',
						templete_name: _this.templete.name,
						
						add_phone: _this.userInfo.phone,
					};
					try {
						const res = await log.addLog(params);
						if(res.status > 0) {
							uni.removeStorageSync('logContent'+_this.templete.id);
							uni.redirectTo({
								url:'/pages/worklog/index?jumpTo=我发出的'
							});
						}
					}catch(e) {
						uni.$u.toast('保存失败');
						this.disabled = false;
					}
				}else {
					const params = {
						id: _this.logObj.id,
						type:1,
						content: JSON.stringify(logContents),
						look_people: _this.logObj.look_people_str,
						
						add_phone: _this.userInfo.phone,
					};
					try {
						const res = await log.editLog(params);
						
						if(res.status > 0) {
							uni.redirectTo({
								url:'/pages/worklog/index?jumpTo=我发出的'
							})
						}
					}catch(e) {
						uni.$u.toast('保存失败');
						this.disabled = false;
					}
					
				}
			},
			selectPerson() {
				uni.navigateTo({
					url: '/components/OrgPicker/index?overlay=overlay&entry=component&VisibleandHidden=true&title=人员选择&source=WorklogAddUser'
				});
			},
			delPerson(index) {
				_this.personList.splice(index, 1);
			},
			lookLog() {
				uni.redirectTo({
					url:'/pages/worklog/index'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		padding-bottom: 50rpx;
		overflow: hidden;
	}
	.header {
		position: relative;
		z-index: 9999;
		padding: 10rpx 20rpx;
		display: flex;
		align-items: center;
		.h-l {
			width: 30%;
			display: flex;
			flex-direction: row;
			gap: 20rpx;
		}
		.h-c {
			width: 40%;
			text-align: center;
		}
		.h-r {
			width: 30%;
			display: flex;
			justify-content: flex-end;
		}
	}
	.content {
		position: relative;
		height: 91vh;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		.scroll-view {
			flex: 1 1 auto;
			width: 99vw; 
			height: 70vh;
			background-color: #f0f0f0;
		}
		.content-item {
			margin-bottom: 20rpx;
			.textarea {
				background-color: #fff;
				padding: 20rpx;
				margin-bottom: 1px;
			}
		}
		.item-list {
			background-color: #fff;
			padding: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.item-list-image {
			margin-bottom: 1px;
			display: flex;
			background-color: #fff;
			padding: 20rpx;
		}
		.item-list-file {
			display: flex;
			background-color: #fff;
			padding: 20rpx;
		}
		.person-list {
			width: 94vw;
			background-color: #fff;
			padding: 0 20rpx 20rpx 20rpx;
			white-space: nowrap;
			.person-item {
				display: flex;
				flex-direction: column; 
				justify-content: center; 
				align-items: center;
				margin-right: 20rpx;
				position: relative;
				image {
					width: 66rpx;
					height: 66rpx;
					border-radius: 5rpx;
				}
				.close-btn {
					position: absolute;
					top: -9px;right: -9px;
					z-index: 999;
				}
			}
		}
		.bottom {
			flex: 0 0 auto; 
			width: 99vw;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			margin: 5rpx 0;
			.left {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-left: 20rpx;
				.TabItemICon{
				  //padding-top: 3px;
				  width: 1.2rem;
				  height: 1.2rem;
				}
			}
			.right {
				width: 80vw;
				//padding-right:20rpx;
				padding-right: 20rpx;
			}
		}
		::v-deep uni-textarea {
			width: 94vw;
			min-height: 60px;
		}
		::v-deep .u-upload__wrap {
			align-items: center;
		}
		::v-deep .lsj-file {
			height: 2em !important;;
		}
	}
</style>
